import {
  Image, Swiper, SwiperItem, Text, View
} from '@tarojs/components'
import React, { useCallback, useState } from 'react';
import Taro from '@tarojs/taro'
import { Analytic_Type } from '@CONSTANTS/analytic'
import Images from '@ASSET/Images'
import Navigate from '@NAVIGATION/navigateManager'
import { getPlatform } from '@UTILS/common'
import i18n from '@I18N'
import style from './PopularSearchBar.module.scss'

const { isWeb } = getPlatform()

const PopularSearchBar = ({
  data, containerClass
}) => {
  const language = 'zh'
  const [curIndex, setCurIndex] = useState(0)
  const onChange = useCallback(e => setCurIndex(e.detail.current), [])
  const onClick = useCallback(
    () => {
      const curData = data[curIndex]
      const { Title } = curData || {}
      const title = Title?.[language]
      Navigate.searchList({ searchPlaceholder: title })
      Taro.tracker.trackEvent(Analytic_Type.num_main_search.eventId)
    },
    [data, curIndex, language],
  )

  const onWebClick = useCallback(() => {
    if (!isWeb) return
    onClick()
  }, [onClick])

  const isEmpty = !Array.isArray(data) || data.length === 0

  return (
    <View className={`${style.container}${containerClass ? ` ${containerClass}` : ''}`}>
      <Image src={Images.search} onClick={onClick} className={style.searchIcon} />
      <View className={style.swipeContainer} onClick={onWebClick}>
        { isEmpty ? <PopularSearchItem language={language} /> : (
          <Swiper
            autoplay
            interval={5000}
            vertical
            circular={data?.length > 1}
            onChange={onChange}
            className={style.swipeContainer}
          >
            {data.map(item => (
              <SwiperItem key={item.p8Id}>
                <PopularSearchItem language={language} key={item.p8Id} data={item} />
              </SwiperItem>
            ))}
          </Swiper>
        )}
      </View>
    </View>
  )
}
const PopularSearchItem = ({ data, language }) => {
  const { Title } = data || {}
  const title = Title?.[language]
  const onClickItem = useCallback(
    () => {
      if (isWeb) return
      Navigate.searchList({ searchPlaceholder: title })
      Taro.tracker.trackEvent(Analytic_Type.num_main_search.eventId)
    },
    [title],
  )
  return (
    <View onClick={onClickItem} className={style.searchContainer}>
      <Text className={style.searchText}>{title || i18n.home.search_placeholder()}</Text>
    </View>
  )
}

export default PopularSearchBar
